package com.bp.hearthealth.pulse.lnapps.bp_utils

import android.os.Handler
import android.os.Looper
import com.bp.hearthealth.pulse.lnapps.bp_extension.LogUtil
import java.lang.ref.WeakReference

interface TimerCallback {
    fun onTimerGreaterThanFifteen()
}

class TimerUtil {
    private var weakHandler: WeakReference<Handler>? = null
    private var elapsedTime: Long = 0
    private var runnable: Runnable? = null
    private var timerCallback: TimerCallback? = null

    fun startTimer(callback: TimerCallback) {
        timerCallback = callback
        if (weakHandler == null || weakHandler?.get() == null) {
            weakHandler = WeakReference(Handler(Looper.getMainLooper()))
        }

        val handler = weakHandler?.get()

        if (runnable == null && handler != null) {
            runnable = object : Runnable {
                override fun run() {
                    elapsedTime += 1000 // 每秒递增
                    updateUI(elapsedTime)
                    handler.postDelayed(this, 1000)
                }
            }
//            handler.postDelayed(runnable!!, 1000)
            handler.post(runnable!!)
        }
    }

    fun resetTimer() {
//        runnable?.let { weakHandler?.get()?.removeCallbacks(it) }
        elapsedTime = 0
//        startTimer(timerCallback!!)
    }

    private fun updateUI(elapsedTime: Long) {
        VibrationUtils.stopVibration()
        LogUtil.i("创建HeartRateActivity开始计时 ${elapsedTime / 1000}")
        // 判断是否超过15秒，触发回调
        if (elapsedTime >= 15000) {
            timerCallback?.onTimerGreaterThanFifteen()
        }
    }

    fun stopTimer() {
        elapsedTime = 0
        runnable?.let {
            weakHandler?.get()?.removeCallbacks(it)
            weakHandler?.clear()
            weakHandler = null
            runnable = null
        }
    }
}

